package org.example.test.producer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangjg
 * @desc
 * @date 2023/05/12 14:59
 **/
@Slf4j
public class TP {

    public static void main(String[] args) {
        String nameSrv = args[0];
        String topicName = args[1];
        int sleepTime = 200;
        long totalCnt = 300;
        int successCnt = 0;
        // 初始化一个producer并设置Producer group name
        DefaultMQProducer producer = new DefaultMQProducer("p1"); //（1）
        // 设置NameServer地址
        producer.setNamesrvAddr(nameSrv);  //（2）
        try {
            List<Message> list = new ArrayList<>();
            // 启动producer
            producer.start();
            for (long i = 1; i <= totalCnt; i++) {
                // 利用producer进行发送，并同步等待发送结果
                Message msg = new Message(topicName /* Topic */,
                        "Tag_" + i /* Tag */,
                        ("Hello RocketMQ " + i + " " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN)).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
                );   //（3）
                msg.setKeys("key1_" + (i % 8));
                msg.putUserProperty("k1", "v1_" + i);
                msg.putUserProperty("k2", "v2_" + i);

                try {
                    SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                        @Override
                        public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                            Long id = (Long) arg;
                            int index = (int) (id % mqs.size());
                            return mqs.get(index);
                        }
                    }, i);   //（4）
                    //                logger.info("--send size={},status={}",list.size(),sendResult.getSendStatus());
                    TimeUnit.MILLISECONDS.sleep(sleepTime);
                    if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
                        log.error("xxxxxxxxxxx sendfail");
                    }else {
                        successCnt++;
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

            TimeUnit.SECONDS.sleep(3);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            // 一旦producer不再使用，关闭producer
            producer.shutdown();
            log.info("producer end. 总记录数={},成功记录数={}",totalCnt,successCnt);
        }
    }

}
